package com.logistics.controller;

import com.logistics.conf.Constants;
import com.logistics.entity.Admin;
import com.logistics.service.AdminService;
import com.logistics.util.JsonUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * Created by Mklaus on 15/8/16.
 */
@Controller
@RequestMapping("admin")
public class AdminController {
    @Resource
    private AdminService adminService;

    @RequestMapping(value = "register",method = RequestMethod.POST)
    public void register(Admin admin,HttpServletResponse resp) throws IOException {
        Admin login = null;
        if (!adminService.isExists(admin.getAdminName())) {
           if((login = adminService.register(admin)) != null) {
               JsonUtil.writeMsg("OK", resp);
           }
        }else {
            JsonUtil.writeMsg("user already exists",resp);
        }

    }

    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String login(){
        return "/admin/adminLogin";
    }

    @RequestMapping("doLogin")
    public String doLogin(String adminName,byte[] password, Model model,HttpSession session){
        Admin login;
        System.out.println("pass = " + password);
        if ((login = adminService.login(new Admin(adminName,password))) != null){
            session.setAttribute(Constants.ADMIN_UID,login.getId());
            model.addAttribute("admin",login);
            return "/admin/loginSuccess";
        }
        return "redirect:/index.jsp";
    }

    @RequestMapping("logout")
    public String logout(HttpServletRequest req){
        req.getSession().removeAttribute(Constants.ADMIN_UID);
        return "redirect:/index.jsp";
    }

    @RequestMapping(value = "/upload",method = RequestMethod.GET)
    public String showUploadPage(){
        return "/admin/uploadFile";
    }

    @RequestMapping(value = "/doUpload",method = RequestMethod.POST)
    public String doUpload(@RequestParam("file") MultipartFile file) throws IOException {
        String pathOnWindow = "f:\\temp\\";
        String pathOnLinux  = "/Users/Mklaus/Desktop/";

        if (!file.isEmpty()){
            System.out.println("path  = " + file.getOriginalFilename());
            FileUtils.copyInputStreamToFile(file.getInputStream(),
                    new File(pathOnLinux,System.currentTimeMillis() + file.getName()+".jpg"));
        }

        return "/success";
    }
}
